<template>
 <view class="">
 	<dLoading :statusing="loading"></dLoading>
 	<view class="" v-if="listPoster[0]&&listPoster[0].img">
 		<!-- <block v-if="isPrivacy">
 			<xh-privacy title="隐私保护指引" theme="direction" @onHandleAgree="onHandle" background="rgba(0, 0, 0, .5)"
 				color="#6C02FA"></xh-privacy>
 		</block> -->
 	    
 		<view :style="{ '--bg-image': `url(${listPoster[0].img})` }" class="bgIndex text-align_center">
 	
 			<view  class="startNow flex" v-if="showBtn" @click="startNowFn()">
 				立即开启  
 			</view>
 	
 		</view> 
 	</view>
 </view>
</template>

<script>
	import dLoading from '@/uni_modules/d-loading/components/d-loading/d-loading.vue'
	function unparam(str = '', unDecodeURI) {
		let result = {};
		let arr = str.split('&');
		arr.forEach((item, idx) => {
			let param = item.split('='),
				name = param[0],
				value = param[1] || '';
			if (name) {
				result[name] = unDecodeURI ? value : decodeURIComponent(value);
			}
		});

		return result;
	}
	export default {
		components: {
           dLoading
		},
		data() {
			return {
				userInfo: uni.getStorageSync("userInfo"),
				isPrivacy: uni.getStorageSync("privacy") ? false : true,
				ellipse: this.$img.ellipse,
				title: 'Hello',
				seconds: '',
				showBtn: false,
				listPoster: [],
				invite: '',
				shareType: '',
				id: '',
				currentIndex: 0,
				loading:false,
				urlJump:''
			}
		},
		// onHandle(e) {
		// 	this.isPrivacy = e;
		// },
		onLoad(options) {

			
			console.log(options)

			let getUrl = window.location.href.split('#')[0];
			// console.log('options', options);
			// let getUrl ='https://dazi.weijuyunke.cn/H5/index.html#/'
			// https://ship.admin168.net/H5/index.html?id=2&currentIndex=1#/00
			// let getUrl = 'https://ship.weijuyunke.net/H5/index.html#/'.split('#')[0];
			// let getUrl = 'https://ship.weijuyunke.net/H5/index.html?invite=wpj98i#/'.split('#')[0];
			// let getUrl='https://dazi.weijuyunke.cn/H5/index.html?invite=h45zcl&code=071sPQ0w3pMl9337nn1w3OHOHn2sPQ00&shareType=1&id=24#/'.split('#')[0];
			// let getUrl='https://dazi.weijuyunke.cn/H5/index.html?invite=h45zcl&code=071sPQ0w3pMl9337nn1w3OHOHn2sPQ00&shareType=2&id=16#/'.split('#')[0];
			// let getUrl='https://dazi.weijuyunke.cn/H5/index.html?invite=h45zcl&currentIndex=2#/'.split('#')[0];
            
			 
			 
			 
			if (getUrl.indexOf('invite') != -1) {
				this.invite = this.getInviteValue(getUrl)
				uni.setStorageSync('invite', this.invite); //缓存登录用户的id

			}

			if (getUrl.indexOf('shareType') != -1) {
				this.shareType = this.getTypeValue(getUrl)
				uni.setStorageSync('shareType', this.shareType);
				this.id = this.getIdValue(getUrl)
				console.log(this.shareType)
				console.log(this.id)
			}
			if (getUrl.indexOf('currentIndex') != -1) {
				this.currentIndex = this.getCurrentIndexValue(getUrl)
				console.log(this.currentIndex)

			}
			if (getUrl.indexOf('url') != -1) {
				this.urlJump = this.getUrlJump(getUrl)
				console.log(this.urlJump)
			
			}




			this.init()
			// this.countdown(1)

		},
		onReady(){
			uni.setNavigationBarTitle({
				title: '加载页'
			});
		},
		onShow() {
			this.$at.releaseKey('submit');
		},
		methods: {

			isToken() {
				setTimeout(() => {
					this.userInfoFn()
				}, 500)
				console.log('onLoad')
			},
			async userInfoFn(token) {
				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');
						console.log(this.userInfo.token)
						const result = await this.$http.post({
							url: this.$api.getGzhUserInfo,
							data: {

								code: wx.getStorageSync('code') ? wx.getStorageSync('code') :
									'02168CFa1G2gDI0RLgIa15sNBo468CFF',
							},
							headers: {
								'Authorization': this.userInfo.token
							}

						})

						if (result.code == 0) {
							console.log(result)
                           this.loading=false
							// 0 老用户 1 新用户
							wx.setStorageSync('is_new_user', result.data.is_new_user);
							if (result.data.is_new_user) {
								this.$at.releaseKey('submit');
								const res = await this.$http.post({
									url: this.$api.glogin,
									data: {

										headimgurl: result.data.headimgurl,
										openid: result.data.openid,
										unionid: result.data.unionid,
										sex: 1,
										nickname: result.data.nickname,
										invite: uni.getStorageSync("invite") ? uni.getStorageSync(
											"invite") : '',

									},
									headers: {

									}

								})

								if (res.code == 0) {
									this.$at.releaseKey('submit');
									uni.removeStorageSync('invite')
									this.$sun.toast('登录成功');
									wx.setStorageSync('userInfo', res.data);
									if (this.shareType == 1) {
										this.$sun.navRe('/pagesB/index/buildSubDetail', {
											id: this.id
										})
									} else if (this.shareType == 2) {
										this.$sun.navRe('/pagesB/index/serviceDetails', {
											id: this.id
										})
									} else if (this.shareType == 3) {
										this.$sun.navRe('/pagesB/index/socialDetails', {
											uid: item.id
										})
									} else {
										this.$sun.navRe('/pages/home/index', {
											currentIndex: this.currentIndex
										});
									}


								} else {

									this.$at.releaseKey('submit');
									uni.removeStorageSync('invite')
									this.$sun.toast(res.message, 'none');
								}

								// this.$sun.navRe('/pages/Login/setUpChildLogin',{...result.data})
							} else {
								uni.removeStorageSync('invite')
								this.$at.releaseKey('submit');
								this.gloginFn(result.data)
							}
						} else {
							this.$sun.toast(result.message, 'none')
							this.$at.releaseKey('submit');
							// this.$sun.navRe('/pages/Login/setUpChildLogin')
						}


						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择

					}
				});



			},
			async gloginFn(data) {
				const result = await this.$http.post({
					url: this.$api.glogin,
					data: {

						openid: data.openid,
						unionid: data.unionid

					},
					headers: {

					}

				})

				if (result.code == 0) {
					uni.removeStorageSync('invite')
					this.$sun.toast('登录成功');
					wx.setStorageSync('userInfo', result.data);
					if(this.urlJump){
						this.$sun.navRe('/'+this.urlJump);
						
					}else{
						
						if (this.shareType == 1) {
							this.$sun.navRe('/pagesB/index/buildSubDetail', {
								id: this.id
							})
						} else if (this.shareType == 2) {
							this.$sun.navRe('/pagesB/index/serviceDetails', {
								id: this.id
							})
						} else if (this.shareType == 3) {
							this.$sun.navTo('/pagesB/index/socialDetails', {
								uid: item.id
							})
						} else {
							this.$sun.navRe('/pages/home/index', {
								currentIndex: this.currentIndex
							});
						}
					}


				} else {
					this.$sun.toast(result.message, 'none');
				}
			},
			getInviteValue(url) {
				var match = url.match(/[?&]invite=([^&/#]*)/);
				if (match) {
					return match[1];
				} else {
					return null; // 如果没有匹配到invite参数，则返回null或者适当的默认值
				}
			},
			getTypeValue(url) {
				var match = url.match(/[?&]shareType=([^&/#]*)/);
				if (match) {
					return match[1];
				} else {
					return null; // 如果没有匹配到invite参数，则返回null或者适当的默认值
				}
			},
			getIdValue(url) {
				var match = url.match(/[?&]id=([^&/#]*)/);
				if (match) {
					return match[1];
				} else {
					return null; // 如果没有匹配到invite参数，则返回null或者适当的默认值
				}
			},
			getCurrentIndexValue(url) {
				var match = url.match(/[?&]currentIndex=([^&/#]*)/);
				if (match) {
					return match[1];
				} else {
					return null; // 如果没有匹配到invite参数，则返回null或者适当的默认值
				}
			},
			getUrlJump(url) {
				var match = url.match(/[?&]url=([^&]+)/);
				if (match) {
					return match[1];
				} else {
					return null; // 如果没有匹配到invite参数，则返回null或者适当的默认值
				}
			},


			async configFn() {
				const res = await this.$http.post({
					url: this.$api.config,
					data: {

					},

				})
				console.log(res)
				if (res.code == 0) {
					this.basicConfiguration = res.data
					wx.setStorageSync('system', res.data);
					if (res.data.gzh_appid) {
						this.appid = res.data.gzh_appid
						console.log(this.appid)
						this.getCode();
					} else {
						this.$sun.toast('请配置appid', 'none')
					}
				} else {
					this.$sun.toast('请配置appid', 'none')
				}
			},
			// 强制关注公众号，获取openid
			getCode() {
				if(!(this.listPoster[0].img)){
					this.loading=true
				}
				
				// if (sessionStorage.getItem("openid") && sessionStorage.getItem("openid") != "undefined") {
				// 	return false;
				// }
				this.code = this.getUrlParam('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
				var local = window.location.href;
				
				// var local = 'https://dazi.weijuyunke.cn';

				var APPID = this.appid;
				if (this.code == null || this.code === '') {
					window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID +
						'&redirect_uri=' + encodeURIComponent(local) +
						'&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect'
						
					
				} else {
					

					this.getOpenId(this.code) //把code传给后台获取用户信息
				}
				
				
				
				
				
			},
			//把code传给后台,得到openid
			getOpenId(code) {

				wx.setStorageSync('code', code);
			
				
				// 这里开始加载动画
				
				
				
				// 本地存储这个openid，并刷新页面
				
				
				if(!(this.listPoster[0].img)){
					this.startNowFn()
				}
				
				
				
				// sessionStorage.setItem("code", code);
			},
			//获取地址栏的参数
			getUrlParam(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				var r = window.location.search.substr(1).match(reg);
				if (r != null) return unescape(r[2]);
				return null;
			},
			countdown(seconds) {

				console.log(seconds);
				if (seconds >= 0) {
					if (seconds == 0) {
						this.showBtn = true
					}
					setTimeout(() => {
						this.seconds = seconds
						this.countdown(seconds - 1);
					}, 1000); // 每隔一秒执行一次
				} else {

					// if(uni.getStorageSync('is_new_user')==0){
					// 	this.startNowFn()
					// }
					// if (wx.getStorageSync('code')) {
					// 	this.startNowFn()
					// }
					// this.$sun.navRe('/pages/index/index')
				}
			},
			startNowFn() {
				this.isToken()

			},

			// 获取轮播图
			async init() {
			
				const resPoster = await this.$http.post({
					url: this.$api.poster,
					data: {

						type: 1

					},
					headers: {
						'Authorization': `Bearer ${this.token}`
					}

				})

				if (resPoster.code == 0) {



					console.log(resPoster.data)
					// 	// 展示区域  1 首页 2 商城 3 套餐卡市场 这里还需要区分


					if (resPoster.data.filter(item => item.type == 1).length) {
						this.listPoster = resPoster.data.filter(item => item.type == 1);
					} else {
						this.listPoster = [{
							img: ''
						}]

					}
					
					console.log(this.listPoster[0].img)
					
					if(this.listPoster[0].img){
						uni.setNavigationBarTitle({
							title: '广告页'
						});
						setTimeout(()=>{
							this.showBtn=true
						},1500)
						
					
					}else{
						uni.setNavigationBarTitle({
							title: '加载中...'
						});
						this.loading=true
					}
					
					this.configFn()
					
					console.log(this.listPoster )
				} else {

					this.$sun.toast(resPoster.message, 'none')
				}
			},

		}
	}
</script>

<style lang="less" scoped>
	.bgIndex {
		position: relative;
		padding: 23rpx;
		background-repeat: no-repeat;
		background-size: cover;
		background-image: (var(--bg-image));
		height: 100vh;

		.Countdown {
			width: 64rpx;
			height: 64rpx;
			box-sizing: border-box;
			border: 2rpx solid rgb(255, 255, 255);
			border-radius: 50%;
			float: right;
		}

		.logo {
			width: 136rpx;
			height: 136rpx;
			border-radius: 50%;
		}

		.titleLogo {
			width: 500rpx;
			height: 400rpx;
		}

		.startNow {
			width: 624rpx;
			position: absolute;
			bottom: 120rpx;
			height: 100rpx;
			// margin: 0 100rpx;
			transform: translate(7%, -50%);
			border-radius: 130rpx;
			color: #fff;
			box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(229, 206, 255, 0.16);
			background: linear-gradient(80.35deg, rgb(171, 81, 255) 0.143%, rgb(120, 93, 246) 99.783%);
		}


	}
</style>